package com.ruoyi.system.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.ListUtil;
import com.ruoyi.system.domain.SysIndustry;
import com.ruoyi.system.mapper.SysIndustryMapper;
import com.ruoyi.system.service.ISysIndustryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 行业字典Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-14
 */
@Service
public class SysIndustryServiceImpl extends ServiceImpl<SysIndustryMapper, SysIndustry> implements ISysIndustryService {


    @Override
    public SysIndustry queryGetById(String id) {
        SysIndustry sysIndustry = this.getById(id);
        return sysIndustry;
    }

    /**
     * 新增行业字典
     *
     * @param sysIndustry 行业字典
     * @return 结果
     */
    @Override
    public boolean addSysIndustry(SysIndustry sysIndustry) {
        boolean save = this.save(sysIndustry);
        return save;
    }

    /**
     * 修改行业字典
     *
     * @param sysIndustry 行业字典
     * @return 结果
     */
    @Override
    public boolean updateSysIndustry(SysIndustry sysIndustry) {
        return this.updateById(sysIndustry);
    }

    @Override
    public List<Tree<String>> getNodeTree() {
        List<SysIndustry> nodeList = this.list();
        List<TreeNode> transNodes = nodeList.stream().map(m -> new TreeNode(m.getId(), m.getParentId(), m.getIndustryName(), "")).collect(Collectors.toList());
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
// 自定义属性名 都有默认值的
        treeNodeConfig.setNameKey("label");
        treeNodeConfig.setIdKey("value");
// 最大递归深度

//转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> treeNodes = TreeUtil.<TreeNode, String>build(transNodes, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId((String) treeNode.getId());
                    tree.setParentId((String) treeNode.getParentId());
                    tree.setWeight(treeNode.getWeight());
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                });
        return treeNodes;
    }

    /**
     * 批量删除行业字典
     *
     * @param ids 需要删除的行业字典主键
     * @return 结果
     */
    @Override
    public boolean deleteSysIndustryByIds(String[] ids) {
        return this.removeByIds(ListUtil.toList(ids));
    }

}
